package module.serial;

import gnu.io.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.TooManyListenersException;

public class UpperMonitor extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextPane textPane;
    private SerialPort serialPort;
    private StringBuilder showMsg = new StringBuilder();
    private SerialPortService serialPortService;


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UpperMonitor frame = new UpperMonitor();
                    frame.setVisible(true);
                    } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public UpperMonitor() {
        serialPortService = new SerialPortService();
        setIconImage(Toolkit.getDefaultToolkit()
                .getImage("D:\\project\\eclipseProject\\workSpace1\\demoFrame\\src\\computer.png"));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 1112, 711);
        contentPane = new JPanel();

        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel label = new JLabel("\u4E32\u53E3");
        label.setBounds(43, 35, 30, 18);
        contentPane.add(label);

        JLabel lblNewLabel = new JLabel("\u6CE2\u7279\u7387");
        lblNewLabel.setBounds(43, 80, 72, 18);
        contentPane.add(lblNewLabel);

        JLabel lblNewLabel_1 = new JLabel("\u6570\u636E\u4F4D");
        lblNewLabel_1.setBounds(43, 124, 72, 18);
        contentPane.add(lblNewLabel_1);

        JLabel lblNewLabel_2 = new JLabel("\u6821\u9A8C\u4F4D");
        lblNewLabel_2.setBounds(43, 166, 72, 18);
        contentPane.add(lblNewLabel_2);

        JLabel label_1 = new JLabel("\u505C\u6B62\u4F4D");
        label_1.setBounds(43, 208, 72, 18);
        contentPane.add(label_1);

        JLabel lblNewLabel_3 = new JLabel("\u6D41\u63A7");
        lblNewLabel_3.setBounds(43, 249, 72, 18);
        contentPane.add(lblNewLabel_3);

        JRadioButton rdbtnAscii = new JRadioButton("ASCII");
        rdbtnAscii.setBounds(43, 335, 72, 27);
        contentPane.add(rdbtnAscii);

        JRadioButton rdbtnNewRadioButton = new JRadioButton("Hex");
        rdbtnNewRadioButton.setBounds(137, 335, 53, 27);
        contentPane.add(rdbtnNewRadioButton);

        JCheckBox chckbxNewCheckBox = new JCheckBox("\u81EA\u52A8\u6362\u884C");
        chckbxNewCheckBox.setBounds(43, 380, 133, 27);
        contentPane.add(chckbxNewCheckBox);

        JCheckBox chckbxNewCheckBox_1 = new JCheckBox("\u663E\u793A\u53D1\u9001");
        chckbxNewCheckBox_1.setBounds(43, 422, 133, 27);
        contentPane.add(chckbxNewCheckBox_1);

        JCheckBox checkBox = new JCheckBox("\u663E\u793A\u65F6\u95F4");
        checkBox.setBounds(43, 462, 133, 27);
        contentPane.add(checkBox);

        JRadioButton radioButton = new JRadioButton("ASCII");
        radioButton.setBounds(43, 523, 72, 27);
        contentPane.add(radioButton);

        JRadioButton radioButton_1 = new JRadioButton("Hex");
        radioButton_1.setBounds(137, 523, 72, 27);
        contentPane.add(radioButton_1);

        JCheckBox checkBox_1 = new JCheckBox("\u91CD\u590D\u53D1\u9001");
        checkBox_1.setBounds(43, 572, 133, 27);
        contentPane.add(checkBox_1);

        JSpinner spinner = new JSpinner();
        spinner.setBounds(145, 573, 31, 24);
        contentPane.add(spinner);

        textPane = new JTextPane();
        textPane.setBounds(284, 38, 600, 411);
        contentPane.add(textPane);

        textField = new JTextField();
        textField.setBounds(284, 486, 500, 100);
        contentPane.add(textField);
        textField.setColumns(10);

        JButton buttonSend = new JButton("发送");
        buttonSend.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message = textField.getText().toString().trim();
                if ("".equals(message)||message=="") {
                    System.out.println("发送内容为空");
                    JOptionPane.showMessageDialog(null, "发送内容不能为空", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                if(serialPort==null) {
                    System.out.println("端口未启动");
                    JOptionPane.showMessageDialog(null, "串口还未打开", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                serialPortService.sendMessage(message+"\n");

            }
        });
        buttonSend.setBounds(792, 523, 113, 27);
        contentPane.add(buttonSend);

        JComboBox comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(new String[] { "1", "2", "3" }));
        comboBox.setBounds(284, 599, 506, 24);
        contentPane.add(comboBox);

        JComboBox comboBoxPort = new JComboBox();
         List<String> coms = serialPortService.getAllAvailbleCom();
        if (coms.size() == 0) {

            JOptionPane.showMessageDialog(null, "没有搜索到有效串口！", "错误", JOptionPane.INFORMATION_MESSAGE);
        } else {
            comboBoxPort.setModel(new DefaultComboBoxModel(coms.toArray()));
        }

        comboBoxPort.setBounds(106, 32, 147, 24);
        contentPane.add(comboBoxPort);

        JComboBox comboBoxBit = new JComboBox();
        comboBoxBit.setModel(new DefaultComboBoxModel(new String[] { "9600", "12000", "15000", "21000" }));
        comboBoxBit.setBounds(106, 77, 147, 24);
        contentPane.add(comboBoxBit);

        JComboBox comboBoxData = new JComboBox();
        comboBoxData.setModel(new DefaultComboBoxModel(new String[] { "8", "7", "6", "5" }));
        comboBoxData.setBounds(106, 121, 147, 24);
        contentPane.add(comboBoxData);

        JComboBox comboBoxCheck = new JComboBox();
        comboBoxCheck.setModel(new DefaultComboBoxModel(new String[] { "None", "Even", "Old", "Mark", "Space" }));
        comboBoxCheck.setBounds(106, 163, 147, 24);
        contentPane.add(comboBoxCheck);

        JComboBox comboBoxStop = new JComboBox();
        comboBoxStop.setModel(new DefaultComboBoxModel(new String[] { "1", "1.5", "2" }));
        comboBoxStop.setBounds(106, 205, 147, 24);
        contentPane.add(comboBoxStop);

        JComboBox comboBoxStream = new JComboBox();
        comboBoxStream.setBounds(106, 239, 147, 24);
        contentPane.add(comboBoxStream);

        JButton openButton = new JButton("打开串口");
        JButton stopButton = new JButton("关闭串口");
        openButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                System.out.println("线程总数:"+Thread.activeCount());
                if (coms.size() == 0) {
                    JOptionPane.showMessageDialog(null, "没有搜索到有效串口！", "错误", JOptionPane.INFORMATION_MESSAGE);
                }
                String comPortName = (String) comboBoxPort.getSelectedItem();
                for (CommPortIdentifier commPortIdentifier : serialPortService.getComPortList()) {
                    if (comPortName.equals(commPortIdentifier.getName())) {
                        try {
                            serialPort = serialPortService.openPort(commPortIdentifier);
                            serialPort.addEventListener(new SerialPortListener());
                            //设置当有数据到达时唤醒监听接收线程
                            serialPort.notifyOnDataAvailable(true);
                            //设置当通信中断时唤醒中断线程
                            serialPort.notifyOnBreakInterrupt(true);

                        } catch (PortInUseException e1) {
                            JOptionPane.showMessageDialog(null, "端口已经被占用！", "错误", JOptionPane.INFORMATION_MESSAGE);
                            e1.printStackTrace();
                            return;
                        } catch (UnsupportedCommOperationException e1) {

                            e1.printStackTrace();
                        } catch (TooManyListenersException e1) {
                            e1.printStackTrace();
                        }

                    }
                }
                System.out.println("串口打开成功!");
                openButton.setEnabled(false);
                stopButton.setEnabled(true);

            }
        });
        openButton.setBounds(950, 136, 113, 27);
        contentPane.add(openButton);

        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("线程总数:"+Thread.activeCount());
                serialPortService.closeComPort(serialPort);
                openButton.setEnabled(true);
                stopButton.setEnabled(false);
            }
        });
        stopButton.setBounds(950, 245, 113, 27);
        contentPane.add(stopButton);
    }
    /**
     *  向面板添加内容
     * */
    public void addContentOnPanel() {
        showMsg.append(serialPortService.receiveMessage());
        textPane.setText(showMsg.toString());
    }


    private class SerialPortListener implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            switch (serialPortEvent.getEventType()) {

                case SerialPortEvent.BI:
                    System.out.println("通讯中断");
                case SerialPortEvent.CD:
                    System.out.println("载波检测");
                case SerialPortEvent.CTS:
                    System.out.println("清除发送");
                case SerialPortEvent.DATA_AVAILABLE:
                    System.out.println("有数据到达哦~~~~");
                    addContentOnPanel();
                    break;
                case SerialPortEvent.DSR:
                    System.out.println("数据设备准备好");
                case SerialPortEvent.FE:
                    System.out.println("帧错误");
                case SerialPortEvent.OE:
                    System.out.println("溢位错误");
                case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                    System.out.println("输出缓冲区已清空");
                case SerialPortEvent.PE:
                    System.out.println("奇偶校验错误");
                case SerialPortEvent.RI:
                    System.out.println("响铃侦测");
                default:
                    break;
            }

        }

    }
    // 发送  [-80, -95, -54, -42, -74, -81, -73, -89, -76, -14, -73, -94, 10]
    // 接受  [48, 33, 74, 86, 54, 47, 55, 39, 52, 114, 55, 34, 10]
}
